const { APP_HOST, APP_PORT } = require("../config/database");
const { createBookImage } = require("../service/file_service")
const { updateImageUrlById } = require("../service/book_service")
const fs = require("fs")
var path = require('path');
class FileController{
    async saveBookInfo(ctx, next) {
        try {
            let { id, bookImage } = ctx.request.body
            var base64Data = bookImage.replace(/^data:image\/\w+;base64,/, "");
            // console.log(base64Data)
            let name = new Date().getTime()+'.png'
            let ImagePath = path.resolve(__dirname, '../uploads/book/'+name);
            var dataBuffer = Buffer.from(base64Data, 'base64');
            await fs.writeFileSync(ImagePath, dataBuffer)
            const result = await createBookImage(name, id);
            const BookImage = `http://${APP_HOST}:${APP_PORT}/book/${id}/image`
            await updateImageUrlById(BookImage, id);
            ctx.body="上传封面成功"
        } catch (error) {
            console.log(error)
        }
       
        // try {
        //     const { filename, mimetype, size } = ctx.req.file;
        //     const { id } = ctx.query;
        //     console.log(id)
        //     console.log(ctx.req.file)
            // try {
            //     const result = await createBookImage(filename, mimetype, size, id);
            //     const BookImage = `http://${APP_HOST}:${APP_PORT}/book/${id}/image`
            //     await updateImageUrlById(BookImage, id);
            //     ctx.body="上传封面成功"
            // } catch (error) {
            //     console.log(error)
            // }
        //     ctx.body="测试成功"
        // } catch (error) {
        //     console.log(error)
        //     ctx.body="测试失败"
        // }
        

    }
}
module.exports=new FileController()